﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BackupGUI
{
    using System.Drawing;
    using System.Runtime.InteropServices;
    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;

    class UIHelper
    {

        public static Icon ImageSource2Icon(ImageSource imageSource)
        {
            BitmapFrame frame = imageSource as BitmapFrame;
            frame = frame.Decoder.Frames[0];

            int width = frame.PixelWidth;
            int height = frame.PixelHeight;
            int stride = width * ((frame.Format.BitsPerPixel + 7) / 8);

            byte[] bits = new byte[height * stride];

            frame.CopyPixels(bits, stride, 0);

            // pin the bytes in memory (avoids using unsafe context)
            GCHandle gcHandle = GCHandle.Alloc(bits, GCHandleType.Pinned);

            Bitmap bitmap = new Bitmap(
                width,
                height,
                stride,
                System.Drawing.Imaging.PixelFormat.Format32bppPArgb,
                gcHandle.AddrOfPinnedObject());

            IntPtr hIcon = bitmap.GetHicon();

            gcHandle.Free();

            return Icon.FromHandle(hIcon);
        }
        
        public static Icon LoadIcon(string iconName)
        {
            var iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/BackupGUI;component/Icons/" + iconName + ".ico")).Stream;
            return new Icon(iconStream);
        }
    }
}
